package com.ztjava.core.base;

import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;

public class BaseService {
	//根据id批量删除
	public void batchDelete(String tablename,String[] ids){
		batchDelete(tablename,"id",ids);
	}
	//批量删除
	public void batchDelete(String tablename,String primaryKey,String[] ids){
		for(String key:ids){
			Db.deleteById(tablename,primaryKey,Integer.parseInt(key));
		}
	}

	public boolean isRepeat(Model model,String tablename,String fields){
		String where = " where "+fields+"='"+model.getStr(fields)+"'";
		if(model.get("id")!=null){
			where = where + " and id<>"+model.getInt("id");
		}
		Record repeat = Db.findFirst("select id from "+tablename+where);
		if(repeat==null){
			return false;
		}else {
			return true;
		}
	}
	public Ret isRepeat(Model model,String tablename,String[]...fields){
		String where = "";
		Ret ret = Ret.create();
		for(String[] item:fields){
			if(item[1].equals("Integer")){
				where = " where "+item[0]+"="+model.getStr(item[0])+"";
			}else if(item[1].equals("String")) {
				where = " where "+item[0]+"='"+model.getStr(item[0])+"'";
			}
			
			if(model.get("id")!=null){
				where = where + " and id<>"+model.getInt("id");
			}
			Record repeat = Db.findFirst("select id from "+tablename+where);
			if(repeat!=null){
				ret.put("result","error");
				ret.put("message", item[2]);
				return ret;
			}
		}
		ret.put("result","success");
		return ret;
	}
}
